using System;
using System.Collections;
using System.Web;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Common;
using log4net;

namespace Sedna.Core.Controls.Actions
{
	/// <summary>
	/// Summary description for ValidateFieldsAreEqualAction.
	/// </summary>
	public class ValidateFieldsAreEqualAction : AbstractValidationAction
	{
		private IList fieldContexts = new ArrayList();
		private string commonPrefix = null;
		private bool useCurrentPrefix = true;
		private bool trunkateCommonContext = true;

		private ILog log = LogManager.GetLogger(typeof(ValidateFieldsAreEqualAction));

		public IList FieldContexts
		{
			get { return fieldContexts; }
			set { fieldContexts = value; }
		}

		public string CommonPrefix
		{
			set { commonPrefix = value; }
		}

		public bool UseCurrentPrefix
		{
			set { useCurrentPrefix = value; }
		}

		public bool TrunkateCommonContext
		{
			set { trunkateCommonContext = value; }
		}

		protected override bool Validate(IExecutionContext executionContext)
		{
			if(FieldContexts.Count == 0)
			{
				return true;
			}

			string currentPrefix = useCurrentPrefix?(string)executionContext["infrastructure.CurrentExecutionContextPrefix"]:this.commonPrefix;
			if(trunkateCommonContext && useCurrentPrefix && currentPrefix != null)
			{
				int lastDotIndex = currentPrefix.LastIndexOf('.');
				currentPrefix = currentPrefix.Substring(0, lastDotIndex);
			}

			object firstValue = executionContext[currentPrefix!=null?(currentPrefix + "." + FieldContexts[0]):FieldContexts[0]];
			foreach(string fieldContext in FieldContexts)
			{
				object currentValue = executionContext[currentPrefix!=null?(currentPrefix+"."+fieldContext):fieldContext];
				if(firstValue == currentValue)
				{
					continue;
				}
				if(firstValue != null && firstValue.Equals(currentValue))
				{
					continue;
				}

				if(log.IsDebugEnabled)
				{
					log.Debug("Validation failed, expected value was=" + firstValue + ", but was="+ currentValue);
				}

				return false;
			}

			return true;
		}
	}
}
